package com.mao.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mao.common.CustomException;
import com.mao.common.Result;
import com.mao.dto.DishDto;
import com.mao.entity.Category;
import com.mao.entity.Dish;
import com.mao.entity.DishFlavor;
import com.mao.mapper.DishMapper;
import com.mao.service.CategoryService;
import com.mao.service.DishFlavorService;
import com.mao.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 保存菜品同时保存口味，保存到两个表dish,dish_flavor
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //要新增菜品可能会对缓存数据不一致，所以先删除该分类的缓存
        String key = "dish:"+dishDto.getCategoryId()+"_status:"+dishDto.getStatus();
        redisTemplate.delete(key);
        //1.将菜品基本信息保存
        this.save(dishDto);
        //2.获取菜品id
        Long id = dishDto.getId();
        //3.获取菜品口味并赋值菜品id
        List<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> flavorList = flavors.stream().map((item) -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());

        //保存口味数据到菜品口味表,用saveBatch主要时保存json数据
        dishFlavorService.saveBatch(flavorList);
    }

    @Override
    public DishDto getWithFlavor(Long id) {
        //同样先查缓存,没有在查mysql
        String key = "dish:"+id;
        DishDto dishDto = (DishDto) redisTemplate.opsForValue().get(key);
        if (dishDto!=null){
            return dishDto;
        }
        dishDto=new DishDto();
        //1.查询菜品基本信息
        Dish dish = this.getById(id);
        //2.创建同时包含菜品基本信息也包含口味的dishDto,并拷贝过去
        BeanUtils.copyProperties(dish,dishDto);
        //3.创建条件构造器
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);
        redisTemplate.opsForValue().set(key,dishDto,30, TimeUnit.MINUTES);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //先删除缓存，以免数据不一致
        String key = "dish:" + dishDto.getCategoryId()+"_status:"+dishDto.getStatus();
        redisTemplate.delete(key);

        //1.更新菜品基本信息
        this.updateById(dishDto);
        //2.删除这个菜品的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        //2.1添加条件
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        //3.重新保存前端传来的口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        //3.1 未口味信息添加菜品id
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public void deleteById(List<Long> ids) {
        //Dish条件构造器
        LambdaQueryWrapper<Dish> queryWrapper1=new LambdaQueryWrapper<>();
        //数据库与传来的ids批量对比
        queryWrapper1.in(Dish::getId,ids);
        //判断是否在起售状态
        queryWrapper1.eq(Dish::getStatus,"1");
        //查询符合在起售状态的菜品，如果有则不能删除，要先停售
        int count = this.count(queryWrapper1);
        if (count>0){
            throw new CustomException("菜品在售卖中，不能删除");
        }else{
            //否则删除菜品
            this.removeByIds(ids);
        }
        //删除菜品对应的口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件判断存在多少一致的菜品id
        queryWrapper.in(DishFlavor::getDishId,ids);
        //然后在进行条件删除
        dishFlavorService.remove(queryWrapper);
    }

    @Override
    public void status(Integer status,List<Long> ids) {
        //1.条件构造器
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        //判断存在多少一致的
        queryWrapper.in(Dish::getId,ids);
        List<Dish> dishList = this.list(queryWrapper);
        //遍历设置更新的状态码，并更新数据库
        for (Dish item:dishList
             ) {
            item.setStatus(status);
            this.updateById(item);
        }
    }

    @Override
    public Page<DishDto> page(int page, int pageSize, String name) {
        //1.分页构造器
        Page<Dish> dishPage=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();
        //2.条件构造器
        //添加过滤条件
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //3.查询分页
        this.page(dishPage,queryWrapper);
        //4.对象拷贝,并忽略records属性
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        //5.要单独处理records属性，所有先拿出来
        List<Dish> records = dishPage.getRecords();
        //6.先遍历records属性，然后通过里面的分类id去查询分类名称
        List<DishDto> dishDtoList = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }else {
                dishDto.setCategoryName("未分类的菜品");
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtoList);
        return dishDtoPage;
    }

    @Override
    public List<DishDto> get_list(Dish dish) {
        //改成先查redis缓存是否有，没有在查mysql数据库
        String key = "dish:"+dish.getCategoryId()+"_status:"+dish.getStatus();
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList!=null){
            return dishDtoList;
        }
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        //添加查询条件
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);//1起售
        queryWrapper.like(dish.getName()!=null,Dish::getName,dish.getName());
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //执行条件查询
        List<Dish> dishList = this.list(queryWrapper);
        dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, item.getId());
            lambdaQueryWrapper.orderByDesc(DishFlavor::getUpdateTime);
            List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        //如果一开始没有缓存到数据库，在这里查完MySQL后会存到redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        //向前端返回查询数据
        return dishDtoList;
    }
}
